/*
 * Copyright (C) 2001-2005 Pleasant nightmare studio
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.pleasantnightmare.noraxidium.util;

import org.apache.log4j.Logger;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Handles application closing and resource disposing in case of crash.
 * Also takes care to notify user.
 * <p/>
 * Note:
 * Be wary when adding code here - buggy code in crash handlers usually makes things complicated :-D
 *
 * @author deus
 * @version 1.0
 * @since Jul 6, 2010 3:07:45 PM
 */
public class CrashExceptionHandler implements Thread.UncaughtExceptionHandler {
  private static final Logger LOGGER = Logger.getLogger(CrashExceptionHandler.class);

  @ParamArg private boolean showCrashDialog;

  public CrashExceptionHandler() {
    showCrashDialog = true;
  }

  public void uncaughtException(Thread t, Throwable e) {
    String stacktrace = createStacktraceString(e);
    String errorMessage = "Application crashed in thread: '" + t.getName()
        + "', error: '" + e.getMessage();
    LOGGER.fatal(errorMessage, e);

    if (showCrashDialog) {
      CrashWindow crashDialog = new CrashWindow(errorMessage, stacktrace);
      crashDialog.setVisible(true);
    }

/*
    JOptionPane.showMessageDialog(
        null,
        errorMessage,
        "Application crash",
        JOptionPane.ERROR_MESSAGE
    );
*/
  }

  private String createStacktraceString(Throwable e) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(stringWriter);
    e.printStackTrace(writer);
    writer.close();

    return stringWriter.toString();
  }
}
